﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace PluginDependencyTest
{

    public class DumpbinAnalyzer
    { 
        public List<string> GetNativeDependencies(string dllPath)
        {
            var dependencies = new List<string>();
            try
            {
                string dumpbinPath = FindDumpbinPath();

                if (string.IsNullOrEmpty(dumpbinPath) ||
                    !File.Exists(dumpbinPath))
                    throw new FileNotFoundException("找不到dumpbin.exe");

                var output = RunDumpbin(dumpbinPath, $"/DEPENDENTS \"{dllPath}\"");

                List<AssemblyName> dlls = AssemblyAnalyzer.ParseAssemblyNames(output);

                var dllName = Path.GetFileName(dllPath);

                foreach (var lib in dlls)
                {
                    if (dllName.Equals(lib.Name))
                        continue;

                    dependencies.Add(lib.Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"依赖分析失败: {ex.Message}");
            }
            return dependencies;
        }

        private string FindDumpbinPath()
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dumpbin.exe");
            if (File.Exists(path))
                return path;

            return Path.Combine(Directory.CreateDirectory(path).Parent?.FullName, "dumpbin.exe");
        }
       
        private string RunDumpbin(string exePath, string arguments)
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = exePath,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true,
                    StandardOutputEncoding = Encoding.GetEncoding(936) // 处理中文编码
                }
            };

            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            return output;
        }

    }
}
